package com.leon.notepad.content;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.leon.notepad.audio.AudioPlayManager;
import com.leon.notepad.audio.IAudioPlayListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.leon.notepad.R;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.leon.notepad.content.adapter.FullyGridLayoutManager;
import com.leon.notepad.content.adapter.GridImagePreviewAdapter;
import com.leon.notepad.content.bean.NotepadBean;
import com.leon.notepad.content.view.VoiceImageView;

import org.litepal.LitePal;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DetailsNotepadActivity extends BaseActivity {

    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.iv_voice)
    VoiceImageView ivVoice;
    @BindView(R.id.recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    private NotepadBean mBean;

    private GridImagePreviewAdapter adapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private static final int REQUEST_SETTING_MONEY = 1011;

    private boolean isRefresh = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details_notepad);
        ButterKnife.bind(this);

        mBean = (NotepadBean) getIntent().getSerializableExtra("item");

        tvContent.setText(mBean.getContent());
        tvTitle.setText(mBean.getTitle());
        if (mBean.getImage() != null && !mBean.getImage().equals("")) {
            List<LocalMedia> list = new Gson().fromJson(mBean.getImage(), new TypeToken<List<LocalMedia>>() {
            }.getType());
            Log.e("1231", "123");
            selectList.addAll(list);
        }
        if (mBean.getSound() == null || mBean.getSound().equals("")) {
            ivVoice.setVisibility(View.GONE);
        }
        initWidget();
    }

    /**
     * 初始化选择图片控件
     */
    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImagePreviewAdapter(this);
        adapter.setList(selectList);
        adapter.setSelectMax(9);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImagePreviewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(DetailsNotepadActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(DetailsNotepadActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(DetailsNotepadActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }


    @OnClick(R.id.iv_voice)
    public void onClick() {
        startPlayRecord(mBean.getSound());
    }

    /**
     * 播放录制的音频
     */
    public void startPlayRecord(String path) {
        File item = new File(path);
        Uri audioUri = Uri.fromFile(item);
        Log.d("P_startPlayRecord", audioUri.toString());
        AudioPlayManager.getInstance().startPlay(this, audioUri, new IAudioPlayListener() {
            @Override
            public void onStart(Uri var1) {
                ivVoice.startPlay();
            }

            @Override
            public void onStop(Uri var1) {
                ivVoice.stopPlay();
            }

            @Override
            public void onComplete(Uri var1) {
                ivVoice.stopPlay();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_details, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.item_modify:
                Intent intent = new Intent(DetailsNotepadActivity.this, AddNotepadActivity.class);
                intent.putExtra("item", mBean);
                intent.putExtra("type", "modify");
                startActivityForResult(intent, REQUEST_SETTING_MONEY);
                break;
            case android.R.id.home:
                if (isRefresh) {
                    Log.e("213", "RESULT_OK");
                    setResult(RESULT_OK);
                }
                finish();
                break;
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SETTING_MONEY && resultCode == RESULT_OK) {
            mBean = LitePal.find(NotepadBean.class, mBean.getId());
            tvContent.setText(mBean.getContent());
            tvTitle.setText(mBean.getTitle());
            if (mBean.getImage() != null && !mBean.getImage().equals("")) {
                List<LocalMedia> list = new Gson().fromJson(mBean.getImage(), new TypeToken<List<LocalMedia>>() {
                }.getType());
                Log.e("1231", "123");
                selectList.clear();
                selectList.addAll(list);
                adapter.notifyDataSetChanged();
            }
            if (mBean.getSound() == null || mBean.getSound().equals("")) {
                ivVoice.setVisibility(View.GONE);
            }
            isRefresh = true;
        }
    }

    @Override
    public void onBackPressed() {
        Log.e("213", "onBackPressed()");
        if (isRefresh) {
            Log.e("213", "RESULT_OK");
            setResult(RESULT_OK);
        }
        finish();
    }
}